package com.zkool.wechat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.utils.JsonUtils;
import com.zkool.wechat.model.User;
import com.zkool.wechat.util.JsonVo;

/**
 * 外出
 * @author zkool
 *
 */
public class UserController extends Controller {

	public void index() {
		setAttr("userPage", User.me.paginate(getParaToInt(0, 1), 10));
		render("index.html");
	}
	
	public void save() {
		// 放数据至session
//		setSessionAttr("loginUser", loginUser);
		// 取数据于session
//		User loginUser = getSessionAttr("loginUser");
		// 删除session中的属性
//		removeSessionAttr("loginUser");
		// 得到HttpSession
//		HttpSession session = getSession();
//		setSessionAttr("loginUser", loginUser);
	}
	
	@SuppressWarnings("unchecked")
	public void login() {
		String wgateid = getPara("wgateid");
		if(StrKit.notBlank(wgateid)){
			User user = User.me.findFirst("select * from my_user where wgateid=?", wgateid);
			if(user != null){
				user.set("login_ip", getIpAddr(getRequest())).set("login_date", new Date()).update();
				setSessionAttr("wechat_user", user);
			}else{
				String wgateUser = getPara("wgateUser");
				if(StrKit.notBlank(wgateUser)){
					Map<String, String> map = JsonUtils.decode(wgateUser, Map.class);
					User newUser = new User();
					newUser.set("wgateid", wgateid).set("open_id", map.get("openid"))
							  .set("nick", map.get("nickname"))
							  .set("sex", map.get("sex"))
							  .set("city", map.get("city"))
							  .set("province", map.get("province"))
							  .set("country", map.get("country"))
							  .set("headimgurl", map.get("headimgurl"))
							  .set("user_type", 0)
							  .set("login_ip", getIpAddr(getRequest()))
							  .set("login_flag", 0)
							  .set("del_flag", 0)
							  .set("login_date", new Date())
							  .set("create_date", new Date());
					newUser.save();
					setSessionAttr("wechat_user", newUser);
				}
			}
		}
		renderJson(new JsonVo(200, "success"));
	}
	
	public String getIpAddr(HttpServletRequest request) {
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    return ip;  
	}  
}
